package cn.dxs.gitee;

import android.app.Application;
import android.content.IntentFilter;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.os.Build;
import android.support.annotation.Nullable;

import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;

import cn.dxs.gitee.dao.DaoMaster;
import cn.dxs.gitee.dao.DaoSession;
import cn.dxs.gitee.service.NetBroadcastReceiver;
import cn.dxs.gitee.util.NetHelper;


/**
 * @author lijian
 * @date 2019-09-20 20:03
 */
public class App extends Application {
    private static final String TAG = App.class.getSimpleName();

    private static App instance;

    private static DaoSession mDaoSession;

    public static App getContext() {
        return instance;
    }

    public static DaoSession getDaoSession() {
        return mDaoSession;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;

        // 初始化应用程序
        long startTime = System.currentTimeMillis();
        initLogger();
        Logger.t(TAG).i("startTime:" + startTime);

        initNetwork();
        initBugly();
        initGreenDao();
        Logger.t(TAG).i("application ok:" + (System.currentTimeMillis() - startTime));
    }

    /**
     * 初始化日志框架
     */
    private void initLogger() {
        FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
                .showThreadInfo(false)  // （可选）是否显示线程信息。默认为true
                .methodCount(0)         // （可选）要显示多少方法行。默认为2
                .methodOffset(7)        // （可选）将内部方法调用隐藏到offset。默认为5
                //.logStrategy(customLog) // （可选）将日志策略更改为打印输出。默认LogCat
                .tag("Gitee-logger--->")   // （可选）每个日志的全局标记。默认PRETTY_LOGGER
                .build();

        Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy) {
            @Override
            public boolean isLoggable(int priority, @Nullable String tag) {
                return BuildConfig.DEBUG;
            }
        });
    }

    /**
     * 初始化网络状态监听
     */
    private void initNetwork() {
        NetBroadcastReceiver receiver = new NetBroadcastReceiver();

        IntentFilter filter;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        } else {
            filter = new IntentFilter();
            filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        }
        registerReceiver(receiver, filter);

        NetHelper.INSTANCE.init(this);
    }

    private void initBugly() {

    }

    private void initGreenDao() {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "gitee.db");
        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        mDaoSession = daoMaster.newSession();
    }
}
